﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Reflection.Metadata;
using Traceability.Common.Domain;
using Traceability.Common.Dtos;
using Traceability.Common.Infrastructure.InterFaces;
using Traceability.Enum;

namespace Traceability.Bais.API.Appliction.Command.Users
{
    public class PermissionCascaderHandler : IRequestHandler<PermissionCascaderCommon, Result<List<PermissionCascaderDto>>>
    {
        private readonly IBaseRepository<Permission> permissionRep;
        private readonly IMapper mapper;
        public PermissionCascaderHandler(IBaseRepository<Permission> _permissionRep,IMapper _mapper)
        {
            permissionRep = _permissionRep;
            mapper = _mapper;
        }


        public async Task<Result<List<PermissionCascaderDto>>> Handle(PermissionCascaderCommon request, CancellationToken cancellationToken)
        {
            var result = new Result<List<PermissionCascaderDto>>() { Code = (int)CommonErrorCode.search};
            var list =await (await permissionRep.GetAll()).Where(c=>c.PerantId==0).ToListAsync();
            List< PermissionCascaderDto> permissionCascaderDtos = new List<PermissionCascaderDto>();
            foreach (var item in list) {
                PermissionCascaderDto permissionCascaderDto = new PermissionCascaderDto();
                permissionCascaderDto.label = item.PermissionName;
                permissionCascaderDto.value = item.PermissionId;
                permissionCascaderDto.children = Cascader(item.PermissionId);
                permissionCascaderDtos.Add(permissionCascaderDto);
            }
            result.list = permissionCascaderDtos;
            return result;
        }

        public List<PermissionCascaderDto> Cascader(int parentId)
        {
            var list = permissionRep.GetAllS().Where(c => c.PerantId == parentId).ToList();
            List<PermissionCascaderDto> permissionCascaderDtos = new List<PermissionCascaderDto>();
            foreach (var item in list)
            {
                PermissionCascaderDto permissionCascaderDto = new PermissionCascaderDto();
                permissionCascaderDto.label = item.PermissionName;
                permissionCascaderDto.value = item.PermissionId;
                permissionCascaderDto.children = Cascader(item.PermissionId);
                permissionCascaderDtos.Add(permissionCascaderDto);
            }

            return permissionCascaderDtos;
        }
    }
}
